package cn.swu.cs.lesson12

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.*
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.lang.StringBuilder
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread

class NewsListActivity : AppCompatActivity() {

    val TAG = "@@NewsListActivity "

    lateinit var mAdapter :NewsListAdapter

    val NEW_URL = "https://api.apiopen.top/getWangYiNews"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_news_list)
        mAdapter = NewsListAdapter()

        findViewById<RecyclerView>(R.id.recycler).apply {
            this.layoutManager = LinearLayoutManager(this@NewsListActivity)
            this.adapter = mAdapter
        }
        loadData()
    }

    private fun loadData() {

//        loadByUrl()
//        loadByOkHttp()
        loadByRetrofit()
    }

    private fun loadByRetrofit() {
        val retrofit = Retrofit.Builder()
            .baseUrl("https://api.apiopen.top/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        val service = retrofit.create(NewsApi::class.java)

        service.getNews().enqueue(object : retrofit2.Callback<ApiResponse<List<News>>>{
            override fun onResponse(
                call: retrofit2.Call<ApiResponse<List<News>>>,
                response: retrofit2.Response<ApiResponse<List<News>>>
            ) {
                val data = response.body()?.result ?: arrayListOf()
                Handler(Looper.getMainLooper()).post {
                    mAdapter.resetData(data)
                }
            }

            override fun onFailure(call: retrofit2.Call<ApiResponse<List<News>>>, t: Throwable) {
                Log.e(TAG,t.message!!)
            }
        })

    }

    private fun loadByOkHttp() {
        val client =  OkHttpClient.Builder().addInterceptor(LoggingInterceptor()).build()

       val request =  Request.Builder()
                .url(NEW_URL)
                .build();

//        thread {
//            val response = client.newCall(request).execute()
//        }
       client.newCall(request).enqueue(object :Callback{
           override fun onFailure(call: Call, e: IOException) {
              Log.e(TAG,e.message!!)
           }

           override fun onResponse(call: Call, response: Response) {
               response.body?.string()?.let {
                   val data = parseJSONString(it)
                   Handler(Looper.getMainLooper()).post {
                       mAdapter.resetData(data)
                   }
               }
           }
       })
    }

    private fun loadByUrl() {
        thread {
            val url = URL(NEW_URL)
            val connect = url.openConnection() as HttpURLConnection
            connect.requestMethod = "GET"
            val stream = connect.inputStream
            val allText = stream.bufferedReader().use(BufferedReader::readText)

            val data = parseJSONString(allText)
            Handler(Looper.getMainLooper()).post {
                mAdapter.resetData(data)
            }
        }
    }

    private fun parseJSONString(json: String): List<News> {
        val gson = Gson()
        val type = object :TypeToken<NewsResp>(){}.type
        val rs = gson.fromJson<NewsResp>(json,type)
        return rs.result
    }

    class NewsListAdapter : RecyclerView.Adapter<NewsListViewHolder>() {

        val data = arrayListOf<News>()

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsListViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_news,parent,false)

            return NewsListViewHolder(view).apply {
                this.img = view.findViewById(R.id.img)
                this.title = view.findViewById(R.id.title)
                this.time = view.findViewById(R.id.time)
            }
        }

        override fun onBindViewHolder(holder: NewsListViewHolder, position: Int) {
           holder.render(data[position])
        }

        override fun getItemCount(): Int {
            return data.size
        }

        fun resetData(arr: List<News>) {
            data.clear()
            data.addAll(arr)
            notifyDataSetChanged()
        }

    }

    class NewsListViewHolder(val view: View): RecyclerView.ViewHolder(view){


        var img:ImageView? = null
        var title:TextView? = null
        var time:TextView? = null

        fun render(news: News) {
            title?.text = news.title
            time?.text = news.passtime
            //
            // img.setImageURI()
            Glide.with(view).load(news.image).into(img!!)
        }
    }
}